<!--
 * @Author: 梁青春
 * @Date: 2025-10-14 16:37:08
 * @LastEditTime: 2025-11-13 08:30:23
 * @LastEditors: 梁青春
-->
<template>
  <div class="hospitalization-info" v-loading="loadingData || loadingForm">
    <h-form :column="3" :model="form" :rules="rules" :readonly="edit" ref="hFormRef">
      <readonly-form-item label="入院时间" prop="admissionTime">
        <el-date-picker
          v-model="form.admissionTime"
          type="datetime"
          value-format="YYYY-MM-DD hh:mm:ss"
          format="YYYY-MM-DD hh:mm"
          placeholder="请选择入院时间"
        />
      </readonly-form-item>
      <readonly-form-item label="科室" prop="deptId">
        <el-select v-model="form.deptId" placeholder="请选择科室" @change="loadWardList">
          <el-option v-for="dept in departmentOptions" :key="dept.deptId" :label="dept.deptName" :value="dept.deptId" />
        </el-select>
      </readonly-form-item>
      <readonly-form-item label="病区" prop="wardId">
        <el-select v-model="form.wardId" placeholder="请选择病区">
          <el-option v-for="dict in wardList" :key="dict.wardId" :label="dict.wardName" :value="dict.wardId" />
        </el-select>
      </readonly-form-item>
      <readonly-form-item label="住院号" prop="hospitalizationNumber">
        <el-input v-model="form.hospitalizationNumber" placeholder="请输入住院号" />
      </readonly-form-item>
      <readonly-form-item label="结算费别" prop="settlementType">
        <el-select v-model="form.settlementType" placeholder="请选择结算费别">
          <el-option v-for="dict in sys_settlement_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </readonly-form-item>
      <readonly-form-item label="入院方式" prop="admissionMethod">
        <el-select v-model="form.admissionMethod" placeholder="请选择入院方式">
          <el-option v-for="dict in sys_admission_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </readonly-form-item>
      <readonly-form-item label="入院病情" prop="admissionCondition">
        <el-select v-model="form.admissionCondition" placeholder="请选择入院病情">
          <el-option v-for="dict in sys_admission_illness" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </readonly-form-item>
      <readonly-form-item label="入院途径" prop="admissionPathway">
        <el-select v-model="form.admissionPathway" placeholder="请选择入院途径">
          <el-option v-for="dict in sys_admission_way" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </readonly-form-item>
      <readonly-form-item label="建议押金" prop="deposit" v-if="isShowDeposit">
        <el-input v-model="form.deposit" placeholder="请输入建议押金" />
      </readonly-form-item>
      <readonly-form-item label="门诊医生" prop="outpatientDoctor" v-else>
        <el-select v-model="form.outpatientDoctor" placeholder="请选择门诊医生">
          <el-option v-for="doctor in doctorList" :key="doctor.userId" :label="doctor.nickName" :value="doctor.userId" />
        </el-select>
      </readonly-form-item>
      <readonly-form-item label="入院诊断" prop="admissionDiagnosis">
        <el-input v-model="form.admissionDiagnosis" placeholder="请输入入院诊断" />
      </readonly-form-item>
    </h-form>
  </div>
</template>
<script setup name="HospitalizationInfo">
import HForm from '@/components/HForm/index.vue'
import { getDepartmentList, getWardOptions } from '@/api/baseinfo/ward'
import { getHospitalizationNo } from '@/api/chargingWork/admissionRegistration'
import { listUserByPostCode } from '@/api/system/user'

const { proxy } = getCurrentInstance()
const { sys_settlement_type, sys_admission_type, sys_admission_illness, sys_admission_way } = proxy.useDict(
  'sys_settlement_type',
  'sys_admission_type',
  'sys_admission_illness',
  'sys_admission_way'
)
const props = defineProps({
  edit: {
    type: Boolean,
    default: false
  },
  patient: {
    type: Object,
    default: () => ({})
  },
  isShowDeposit: {
    type: Boolean,
    default: false
  }
})
const form = ref({
  admissionTime: null,
  deptId: '',
  wardId: '',
  hospitalizationNumber: '',
  settlementType: '',
  admissionMethod: '',
  admissionCondition: '',
  admissionPathway: '',
  outpatientDoctor: '',
  admissionDiagnosis: ''
})
const loadingData = ref(false)
const loadingForm = ref(false)

watch(
  () => props.patient,
  newVal => {
    loadingForm.value = true
    if (newVal) {
      form.value = {
        ...form.value,
        ...newVal,
        deptId: Number(newVal.deptId) || '',
        outpatientDoctor: Number(newVal.outpatientDoctor) || ''
      }
      loadingForm.value = false
    }
  },
  {
    immediate: true,
    deep: true
  }
)

const rules = ref({
  admissionTime: [{ required: true, message: '请选择入院时间', trigger: 'blur' }],
  deptId: [{ required: true, message: '请选择科室', trigger: 'blur' }],
  wardId: [{ required: true, message: '请选择病区', trigger: 'blur' }],
  settlementType: [{ required: true, message: '请选择结算费别', trigger: 'blur' }],
  admissionPathway: [{ required: true, message: '请选择入院途径', trigger: 'blur' }]
})

const departmentOptions = ref([])
const wardList = ref([])
const doctorList = ref([])
// 获取科室列表
const loadDepartmentList = async () => {
  // 中文注释：防御式判断，避免在 form 尚未就绪或返回空列表时访问越界
  const res = await getDepartmentList({ deptType: 4 })
  if (res.code === 200) {
    const list = Array.isArray(res.data) ? res.data : []
    departmentOptions.value = list
    if (list.length > 0 && list[0]?.deptId != null) {
      form.value.deptId = form.value.deptId ?? list[0].deptId
    }
  }
}

// 获取病区列表
const loadWardList = async () => {
  // 中文注释：当科室未选择时直接清空病区并返回，避免无效请求与潜在报错
  wardList.value = []
  const res = await getWardOptions({ deptId: form.value.deptId })
  if (res.code === 200) {
    const list = Array.isArray(res.data) ? res.data : []
    wardList.value = list
    if (list.length > 0 && list[0]?.wardId != null) {
      form.value.wardId = form.value.wardId ?? list[0].wardId
    }
  }
}

// 获取医生列表
const loadDoctorList = async () => {
  const res = await listUserByPostCode('doctor')
  if (res.code === 200) {
    doctorList.value = res.rows.map(item => ({
      ...item,
      value: item.userId,
      label: item.nickName || item.userName
    }))
  }
}

// 获取住院号
const getHospitalizationNumber = async () => {
  const res = await getHospitalizationNo()
  return new Promise((resolve, reject) => {
    if (res.code === 200) {
      resolve(res.data)
    } else {
      reject(res.msg)
    }
  })
}

// 暴露表单数据
const exposeForm = () => {
  return new Promise((resolve, reject) => {
    proxy.$refs['hFormRef'].validate((valid, fields) => {
      if (valid) {
        resolve(form.value)
      } else {
        reject(fields)
      }
    })
  })
}

defineExpose({
  exposeForm
})

const init = async () => {
  loadingData.value = true
  form.value.admissionTime = proxy.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
  form.value.hospitalizationNumber = (await getHospitalizationNumber()) ?? ''
  await loadDepartmentList()
  loadWardList()
  loadDoctorList()
  const st = setTimeout(() => {
    loadingData.value = false
    clearTimeout(st)
  }, 500)
}

init()
</script>
